package com.ztesoft.report.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ztesoft.report.base.pojo.R;
import com.ztesoft.report.base.service.impl.BaseServiceImpl;
import com.ztesoft.report.dao.TempUploadLogDao;
import com.ztesoft.report.entity.Report;
import com.ztesoft.report.entity.ReportUpload;
import com.ztesoft.report.entity.TempUploadLog;
import com.ztesoft.report.exception.RException;
import com.ztesoft.report.service.TempUploadLogService;
import com.ztesoft.report.utils.AESUtil;
import com.ztesoft.report.utils.ftp.SftpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 上传日志表 服务实现类
 * </p>
 *
 * @author y3tu
 * @since 2018-06-26
 */
@Service
@Slf4j
public class TempUploadLogServiceImpl extends BaseServiceImpl<TempUploadLogDao, TempUploadLog> implements TempUploadLogService {
    @Autowired
    TempUploadLogDao tempUploadLogDao;

    @Override
    public R queryPage(Map<String, Object> map) {
        int current = (int) map.get("current");
        int size = (int) map.get("size");
        PageHelper.startPage(current, size);
        List<TempUploadLog> list = null;
        try{
            list = tempUploadLogDao.queryPages(map);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        PageInfo<Map<String, Object>> page = new PageInfo(list);
        return R.ok(page);
    }

    @Override
    public void uploadExcel(ReportUpload reportUpload, String localUrl) {
        String password = AESUtil.decrypt(reportUpload.getPassword());
        try {
            SftpClient sftpClient = SftpClient.connect(reportUpload.getHost(), Integer.parseInt(reportUpload.getPort()),
                    reportUpload.getUsername(), password, 2000, 2000);
            sftpClient.put(localUrl,reportUpload.getUploadPath());
            log.info("文件上传成功！");
            sftpClient.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RException("文件上传至服务器失败！");
        }
        //删除本地文件
        File file = new File(localUrl);
        if (file != null && file.exists()) {
            file.delete();
        }
    }

    @Override
    public void deleteFileOnServer(ReportUpload reportUpload,String fileName) {
        String password = AESUtil.decrypt(reportUpload.getPassword());
        try {
            SftpClient sftpClient = SftpClient.connect(reportUpload.getHost(), Integer.parseInt(reportUpload.getPort()),
                    reportUpload.getUsername(), password, 2000, 2000);
            sftpClient.deleteFile(reportUpload.getUploadPath() + "/" + fileName);
            sftpClient.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RException(fileName+"文件删除失败");
        }
    }
}
